package com.hsxc.cdz.controller.wxController.util;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.apache.log4j.Logger;




/** 
* @author  wpfei
* @version 创建时间：2016年7月5日 上午13:44:06 
* 类说明 ：
*/
public class PropertiesUtil {
	protected static Logger log = Logger.getLogger("PropertiesUtil");

	private Properties props;
	private String fileName;
	private FileInputStream inputFile;  
	private FileOutputStream outputFile;  
	  
	
	public  Properties getProps() {
		return props;
	}
	public void setProps(Properties props) {
		this.props = props;
	}
	
		
	public PropertiesUtil(String fileName){
		this.fileName=fileName;
		readProperties(fileName);
	}
	
	public void readProperties(String fileName) {
		props = new Properties();  
	        try {
	        	//inputFile = new FileInputStream(getClass().getClassLoader().getResource(fileName).getPath());
            	inputFile = new FileInputStream(fileName);  
            	log.info("--------------------------加载配置文件---------------------------------------");
	            props.load(inputFile);  
	            log.info("--------------------------准备写入配置文件-------------------------------------");
	          //  inputFile.close();  
	        } catch (FileNotFoundException ex) {  
	        	log.info("读取属性文件--->失败！- 原因：文件路径错误或者文件不存在");  
	            ex.printStackTrace();  
	        } catch (IOException ex) {  
	        	log.info("装载文件--->失败!");  
	            ex.printStackTrace();  
	        } 
	}
	/**
	 * 获取某个属�??
	 */
	public String getProperty(String key){
		System.out.println("-----------------------------------获取配置文件的值------------------------------------");
		return props.getProperty(key);
	}
	/**
	 * 可以试试props.putAll(t)
	 */
	public Map getAllProperty(){
		Map map=new HashMap();
		Enumeration enu = props.propertyNames();
		while (enu.hasMoreElements()) {
			String key = (String) enu.nextElement();
			String value = props.getProperty(key);
			map.put(key, value);
		}
		return map;
	}
//	
	/**
	 * 在控制台上打印
	 */
	public void printProperties(){
		props.list(System.out);
	}
	/**
	 * 写入properties信息
	 */
    public void writeProperties(String key, String value) {
		try {
			log.info("-------------------------写入数据到配置文件-------------------------------------");
			outputFile = new FileOutputStream(fileName);
			props.setProperty(key, value);
			// 将此 Properties 表中的属性列表（键和元素对）写入输出�?
			props.store(outputFile, key);
			outputFile.flush();
			log.info("-------------------------------写入数据成功-----------------------------------");
		} catch (IOException e) {
			e.printStackTrace();
		}
		}   
    
}

